/**
 * ...
 * @author Yog
 */

package cookinmaddy.client.view;
import com.yff.controls.FButton;
import com.yff.controls.FDiv;
import com.yff.controls.FInput;
import com.yff.controls.FText;
import cookinmaddy.model.Recipe;
import cookinmaddy.client.Ajax;

import haxe.Serializer;
import haxe.Unserializer;


class RecipeControlView
{
	private var self : RecipeControlView ;
	private var _container : FDiv;
	private var _recipe : Recipe;
	private var _callBack : Dynamic;
	private var _addmode : Bool;
	public function new(callBack : Dynamic, container : FDiv, recipe : Recipe, addMode : Bool) 
	{
		self = this;
		_callBack = callBack;
		_container = container;
		_recipe = recipe;
		_addmode = addMode;
	}
	
	public function show()
	{
		_container.appendChild(new FText("Recipe name:"));
		var recipeName : FInput = new FInput();
		recipeName.id = "recipename";
		recipeName.value = _recipe.Name;
		_container.appendChild(recipeName);
		_container.appendChild(FText.endl);
		if (_addmode)
		{
			var btn : FButton = new FButton("Add");
			btn.addEvent("click", self.onClick_Add,  { div : _container } );
			_container.appendChild(btn);
		}
		else
		{
			var btn : FButton = new FButton("Update");
			btn.addEvent("click", self.onClick_Update,  { div : _container } );
			_container.appendChild(btn);
		}
		
		_container.appendChild(FText.endl);
		_container.appendChild(new FText("list:"));
		
		
	}	
	
	public function onClick_Add(arg : Dynamic)
	{
		var div : FDiv = arg.div;
		var l : Int = div.childNodes.length;
		for(tmp in div.childNodes)
		{
			var txt : FText = cast tmp ;
			switch(txt.id)
			{
				case "recipename":
					_recipe.Name = txt.value;
				default:
			}
		}
		
		var data = Serializer.run(_recipe);	
		
		var req = "?action=addrecipe&data=" + data;
		StringTools.htmlEscape(req);
		
		Ajax.getContentAsync(req, _callBack);			
	}
	
	public function onClick_Update(arg : Dynamic)
	{
		var div : FDiv = arg.div;
		var l : Int = div.childNodes.length;
		for(tmp in div.childNodes)
		{
			var txt : FText = cast tmp ;
			switch(txt.id)
			{
				case "recipename":
					_recipe.Name = txt.value;
				default:
			}
		}
		
		var data = Serializer.run(_recipe);	
		
		var req = "?action=updaterecipe&data=" + data;
		StringTools.htmlEscape(req);
		
		Ajax.getContentAsync(req, _callBack);			
	}
}